package com.onpositive.pictureviewer;

import java.io.File;
import java.util.ArrayList;

import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import org.eclipse.core.runtime.Preferences.PropertyChangeEvent;
import org.eclipse.pde.core.plugin.IPluginModelBase;
import org.eclipse.pde.core.plugin.PluginRegistry;
import org.eclipse.pde.core.plugin.TargetPlatform;
import org.eclipse.pde.internal.core.ICoreConstants;
import org.eclipse.pde.internal.core.PDECore;

@SuppressWarnings("restriction")
public class PlatformImages extends AbstractImageEntry implements IImageStore {

	private String location;

	private static PlatformImages instance;

	public String getName() {
		return "Target Platform";
	}

	protected void initPlatform() {
		IPluginModelBase[] externalModels = PluginRegistry.getExternalModels();
		for (IPluginModelBase b : externalModels) {
			String installLocation = b.getInstallLocation();
			if (installLocation != null) {

				File f = new File(installLocation);
				if (f.getName().charAt(0) == '.') {
					continue;
				}
				// System.out.println(f);
				final ArrayList<IImageEntry> z = new ArrayList<IImageEntry>();
				final ItemGroup group = new ItemGroup(f.getName(), z);
				this.parse(z, f, f);
				if (group.getChildCount() > 0) {
					this.fetched(group);
				}

			}
			this.fireChanged();
		}
	}

	private PlatformImages() {
		final Preferences preferences = PDECore.getDefault()
				.getPluginPreferences();
		final IPropertyChangeListener propertyChangeListener = new IPropertyChangeListener() {

			public void propertyChange(PropertyChangeEvent event) {
				if (event.getProperty().equals(ICoreConstants.PLATFORM_PATH)) {
					PlatformImages.this.initPlatform();
				}
			}

		};
		preferences.addPropertyChangeListener(propertyChangeListener);
		this.init();
	}

	public static PlatformImages getInstance() {
		if (PlatformImages.instance == null) {
			PlatformImages.instance = new PlatformImages();
		}
		return PlatformImages.instance;
	}

	public File getFile() {
		this.location = TargetPlatform.getLocation();
		final File file = new File(this.location, "plugins");

		return file;
	}

}
